<template>
  <div>
    <el-card>
      <el-alert
        title="添加商品信息"
        type="info"
        center
        show-icon
        :closable="false"
      >
      </el-alert>
      <!-- 步骤条 -->
      <el-steps
        :active="stepActive * 1"
        finish-status="success"
        :align-center="true"
        style="margin-top: 10px"
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <el-form
        ref="addGoodsInfoFormRef"
        :model="addGoodsInfoForm"
        :rules="addGoodsInfoFormRules"
        label-width="80px"
      >
        <!-- 垂直方向 -->
        <el-tabs
          tab-position="left"
          style="margin-top: 20px"
          :before-leave="beforeLeave"
          v-model="stepActive"
          @tab-click="changeTab"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addGoodsInfoForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addGoodsInfoForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addGoodsInfoForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addGoodsInfoForm.goods_number"></el-input>
            </el-form-item>
            <!-- 商品分类需要使用级联选择器去渲染  找商品分类的数据 -->
            <el-form-item label="商品分类">
              <el-cascader
                v-model="addGoodsInfoForm.goods_cat"
                :options="goodsCateOptions"
                :props="{ expandTrigger: 'hover', ...goodsCateOptionsProps }"
                @change="getGoodsCateChange"
                style="width: 100%"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <!-- 当点击商品参数时 this.stepActive == '1' 请求动态参数
                当点击商品属性时 this.stepActive == '2' 请求静态参数
                谁能监听到tabs切换  @tab-click能监听到tab切换
           -->
          <!-- 动态参数 -->
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              :label="item.attr_name"
              v-for="item in manyCateData"
              :key="item.attr_id"
            >
              <el-checkbox-group
                v-model="item.attr_vals"
                @change="handleCheckedAttrValsChange"
              >
                <el-checkbox
                  v-for="el in item.attr_vals"
                  :key="el"
                  :label="el"
                  border
                  >{{ el }}</el-checkbox
                >
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <!-- 静态参数 -->
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              :label="item.attr_name"
              v-for="item in onlyCateData"
              :key="item.attr_id"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              class="upload-demo"
              action="http://127.0.0.1:8888/api/private/v1/upload"
              :on-remove="handleRemovePic"
              :on-success="handleSuccessPic"
              list-type="picture"
              :headers="headersObj"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb
              </div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor
              ref="quillEditorRef"
              v-model="addGoodsInfoForm.goods_introduce"
            >
            </quill-editor>
            <el-button type="primary" @click="addGoods">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { goods_cate_req, add_goods_info_req } from "@/api/goods.js";
import { cate_params_req } from "@/api/cateParams.js";
import { quillEditor } from "vue-quill-editor";
import _ from "lodash";

import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
export default {
  data() {
    return {
      stepActive: "0",
      //收集的添加商品的参数 form
      addGoodsInfoForm: {
        goods_name: "",
        goods_price: 1,
        goods_weight: 1,
        goods_number: 1,
        // 最终这个数据需要被整理
        goods_cat: [],
        attrs: [],
        // 收集图片的
        pics: [],
        goods_introduce: "",
      },
      addGoodsInfoFormRules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" },
        ],
      },
      /* //  级联选择器选中的数据
      selectedKeys: [], */
      //   级联选择器渲染的商品分类
      goodsCateOptions: [],
      //   级联选择器props
      goodsCateOptionsProps: {
        label: "cat_name",
        value: "cat_id",
        children: "children",
      },
      // 动态分类参数
      manyCateData: [],
      // 静态分类参数
      onlyCateData: [],
      headersObj: {
        Authorization: sessionStorage.getItem("token"),
      },
    };
  },
  mounted() {
    this.getGoodsCateList();
  },
  methods: {
    async getGoodsCateList() {
      const result = await goods_cate_req({});
      console.log(result);
      this.goodsCateOptions = result.data;
    },
    getGoodsCateChange() {
      console.log(this.selectedKeys);
    },
    beforeLeave(activeName, oldActiveName) {
      console.log(activeName, oldActiveName);
      console.log("xx");
      //   return false;
      //  只有在基本信息 tab  商品名称和商品分类如果没有 为false
      //   要在基本信息页面tab oldActiveName == 0
      // 商品名称 addGoodsInfoForm.goods_name
      // 商品分类 this.selectedKeys.length 3

      if (
        oldActiveName === "0" &&
        this.addGoodsInfoForm.goods_name === "" &&
        this.selectedKeys.length !== 3
      ) {
        this.$message.error("请填写商品名称和商品分类");
        return false;
      }
    },
    // tab切换触发的事件
    async changeTab() {
      // console.log("tab切换");
      if (this.stepActive === "1") {
        // 请求动态参数
        const result = await cate_params_req({
          method: "get",
          url: `categories/${this.cateId}/attributes`,
          params: {
            sel: "many",
          },
        });
        console.log(result);
        if (result.meta.status !== 200) {
          return this.$message.error("参数请求失败");
        }
        // 需要将attr_vals 字符串转变为数组， 注意 万一字符串为空串
        result.data.forEach(
          (item) =>
            (item.attr_vals =
              item.attr_vals.length == 0 ? [] : item.attr_vals.split(" "))
        );
        this.manyCateData = result.data;
      }
      if (this.stepActive === "2") {
        // 请求静态参数
        const result = await cate_params_req({
          method: "get",
          url: `categories/${this.cateId}/attributes`,
          params: {
            sel: "only",
          },
        });
        console.log(result);
        if (result.meta.status !== 200) {
          return this.$message.error("参数请求失败");
        }
        this.onlyCateData = result.data;
      }
    },
    handleCheckedAttrValsChange() {
      console.log("xxxchange");
      // 最终准备提交服务器进行商品信息添加的对象
      // console.log(this.addGoodsInfoForm.attr_vals);
      // 动态参数数据
      console.log(this.manyCateData);
      // 最后收集完数据之后manyCateData、onlyCateData数据是最新的，需要更新this.addGoodsInfoForm.attrs
    },
    // 删除图片会触发的函数
    handleRemovePic(file, fileList) {
      console.log(file, fileList);
      const filePath = file.response.data.tmp_path;
      const index = this.addGoodsInfoForm.pics.findIndex(
        (item) => item.pic === filePath
      );
      // 找到index之后进行删除即可
      this.addGoodsInfoForm.pics.splice(index, 1);
      console.log(this.addGoodsInfoForm.pics);
    },
    // 上传成功会触发的钩子函数
    handleSuccessPic(response) {
      console.log(response);
      // 收集上传成功的图片的路径
      const picInfo = { pic: response.data.tmp_path };
      // 将收集到的数据放到pics当中
      this.addGoodsInfoForm.pics.push(picInfo);
      console.log(this.addGoodsInfoForm.pics);
    },
    // 添加商品
    async addGoods() {
      // 表单验证成功之后
      console.log(this.addGoodsInfoForm);
      // goods_cat 需要处理称为以逗号分割的字符串 join
      // attrs 需要从manyCateData onlyCateData中把数据拿到
      /* this.addGoodsInfoForm.goods_cat =
        this.addGoodsInfoForm.goods_cat.join(","); */
      // 有可能会报错 因为强改字符串  级联选择器 数组
      // 再复制一个新对象   this.addGoodsInfoForm 独立
      const newForm = _.cloneDeep(this.addGoodsInfoForm);
      newForm.goods_cat = newForm.goods_cat.join(",");

      this.manyCateData.forEach((el) => {
        const newInfo = { attr_id: el.attr_id, attr_vals: el.attr_vals };
        newForm.attrs.push(newInfo);
      });
      this.onlyCateData.forEach((item) => {
        const newInfoOnly = {
          attr_id: item.attr_id,
          attr_vals: item.attr_vals,
        };
        newForm.attrs.push(newInfoOnly);
      });
      console.log(newForm);
      const result = await add_goods_info_req(newForm);
      console.log(result);
      if (result.meta.status !== 201) {
        return this.$message.error("添加商品失败");
      }
      this.$router.push("/goods");
      return this.$message.success("添加商品成功");
    },
  },
  computed: {
    cateId() {
      if (this.addGoodsInfoForm.goods_cat.length === 3) {
        return this.addGoodsInfoForm.goods_cat[
          this.addGoodsInfoForm.goods_cat.length - 1
        ];
      }
      return null;
    },
  },
  components: {
    quillEditor,
  },
};

/* 
需求：
在基本信息tab页当中必须先填写了商品名称和商品分类才能进入商品参数，否则弹出警告窗 没有填写商品名称和商品分类，不能进入
tab组件帮咱们进行跳转 


*/
</script>

<style lang="scss" scoped>
</style>